package com.hemerasolutions.v2trainer.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.event.ActionEvent;

import org.primefaces.event.FileUploadEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.hemerasolutions.v2trainer.component.interfaces.table.EquipmentTableCompInterface;
import com.hemerasolutions.v2trainer.controller.interfaces.TeacherBeanInterface;
import com.hemerasolutions.v2trainer.model.exercise.Equipment;
import com.hemerasolutions.v2trainer.model.multimedia.Photo;
import com.hemerasolutions.v2trainer.model.users.Academy;
import com.hemerasolutions.v2trainer.model.users.Teacher;
import com.hemerasolutions.v2trainer.model.users.User;
import com.hemerasolutions.v2trainer.service.ExceptionService;
import com.hemerasolutions.v2trainer.service.interfaces.LibraryServiceInterface;
import com.hemerasolutions.v2trainer.service.interfaces.UserServiceInterface;


@Controller
@ManagedBean(name="teacherBean")
@Scope("view")
public class TeacherBean extends BaseBean implements TeacherBeanInterface {


	private static final long serialVersionUID = 1L;

	@Autowired
	private UserServiceInterface userService;
	
	@Autowired
	private LibraryServiceInterface libraryService;
	
	@Autowired
	private EquipmentTableCompInterface equipmentTable;
	
	private List<Teacher> teachers;
	
	private Teacher selTeacher;
	
	private Teacher teacher;
	
	private int uploadType;
	
	private Date 		begCreatedAt;
    
	private Date 		endCreatedAt;
    
	private Date 		begChangedAt;
    
	private Date 		endChangedAt;

	private Date 		begExpireOn;
    
	private Date 		endExpireOn;

	private String 		findByName;
    
	private String 		findByLastName;

	private String 		findByCpf;

	private String 		findByEmail;
    
	private boolean 	findByStatus = true;	
	
	
	public TeacherBean() {
		super();
	}

	@PostConstruct
	public void init(){
		super.init();
		if(this.getActiveUserType() == User.USERTYPE_TEACHER){
			this.teacher = this.getActiveActor(Teacher.class);
			this.loadAcademyEquipments();
		}else{
			this.listAll();
		}

	}

	public void loadAcademyEquipments(){
		this.equipmentTable.setEquipments(new ArrayList<Equipment>());
		this.equipmentTable.getEquipments().addAll(this.teacher.getAcademy().getEquipments());
		this.equipmentTable.refresh();		
	}
	
	public void saveEquipments(){
		Academy academy = this.getTeacher().getAcademy();
		academy.setEquipments(this.equipmentTable.getEquipments());
		try {
			userService.saveAcademy(academy);
			this.showInfoMessage(	this.localizedText("SavedWithSuccess"),
					this.localizedText("TheAcademy") + " " +
					academy.getName() + "\n , " + 
					this.localizedText("wasSavedWithSuccess"));			
			this.listAll();
			
		} catch (ExceptionService e) {
			this.showErrorMessage(this.localizedText("SaveError"), e.getLocalizedMessage());
		}
	}
	
	private void listAll() {

	   	Map<String,Object> fields = new HashMap<String, Object>();

    	Academy academy = null;
    		   	
	   	
		if(this.getActiveUserType() == User.USERTYPE_ACADEMY){
			academy = this.getActiveActor(Academy.class);
		}
	   	
	 
		if( academy != null){
			fields.put("academy", academy);
		}
				
	   	this.teachers = this.userService.searchTeachers(fields);
	}		

	public void clear(){
		this.teacher = null;
	}

	
	public void createTeacher(){
		try {
			if(this.getActiveUserType() == User.USERTYPE_ACADEMY){	
				this.teacher.setAcademy(this.getActiveActor(Academy.class));
			}
			userService.createTeacher(teacher);
			this.showInfoMessage(	this.localizedText("CreatedWithSuccess"),
					this.localizedText("TheTeacher") + " " +
					this.teacher.getFirstName() + "\n , " + 
					this.localizedText("wasCreatedWithSuccess"));			
			this.teacher = null;
			this.listAll();
		} catch (ExceptionService e) {
			this.showErrorMessage(this.localizedText("CreateError"), e.getLocalizedMessage());
			e.printStackTrace();
		}
	}
	
	
	public void saveTeacher(){
		try {
			userService.saveTeacher(teacher);
			this.showInfoMessage(	this.localizedText("SavedWithSuccess"),
					this.localizedText("TheTeacher") + " " +
					this.teacher.getFirstName() + "\n , " +
					this.localizedText("wasSavedWithSuccess"));			
			this.teacher = null;
			this.listAll();
			
		} catch (ExceptionService e) {
			this.showErrorMessage(this.localizedText("SaveError"), e.getLocalizedMessage());
		}
	}
	
	public void cancelChange(){
		if(this.teacher.getId() != 0){
			this.teacher = userService.readTeacher(teacher);
		}else{
			this.teacher = new Teacher();
		}
	}

	public void uploadPhoto(FileUploadEvent ev){
		

		Photo photo = new Photo();

		photo.setName("user_photo");
		photo.setHeight(120);
		photo.setWidth(100);
		
		teacher.setPhoto(super.uploadPhoto(ev, photo));
		teacher.setPhoto(userService.savePhoto(photo));

	}
	

	
	public void search(ActionEvent event){

    	Map<String,Object> fields = new HashMap<String, Object>();
    	

    	Academy academy = null;
    		   	
	   	
    	
		if( this.begCreatedAt != null && this.endCreatedAt != null && 
				this.begCreatedAt.compareTo(this.endCreatedAt) > 0){
				this.showErrorMessage(	this.localizedText("CreationDate"),
										this.localizedText("TheInitialDateNeedToBeGreaterThanFinal"));
				return;
			}
			

		if( this.begChangedAt != null && this.endChangedAt != null && 
			this.begChangedAt.compareTo(this.endChangedAt) > 0){
			this.showErrorMessage(	this.localizedText("ChangeDate"),
									this.localizedText("TheInitialDateNeedToBeGreaterThanFinal"));
			return;			
		}
    	
		if( this.begExpireOn != null && this.endExpireOn != null && 
				this.begExpireOn.compareTo(this.endExpireOn) > 0){
				this.showErrorMessage(	this.localizedText("ExpireDate"),
										this.localizedText("TheInitialDateNeedToBeGreaterThanFinal"));
				return;
			}
    	

		if(this.getActiveUserType() == User.USERTYPE_ACADEMY){
			academy = this.getActiveActor(Academy.class);
		}
	   	
	 
		if( academy != null){
			fields.put("academy", academy);
		}
				
    	if (!this.findByName.equals("")) {
            fields.put("firtName", this.findByName);
        }

    	if (!this.findByName.equals("")) {
            fields.put("lastName", this.findByName);
        }
    	
    	if (!this.findByEmail.equals("")){
    		fields.put("email",this.findByEmail);
    	}
    	
    	if (this.begCreatedAt != null){
    		fields.put("begCreatedAt", this.begCreatedAt);
    	}
    	if (this.endCreatedAt != null){
            fields.put("endCreatedAt",this.endCreatedAt);
        }
        if (this.begChangedAt != null){
        	fields.put("begChangedAt",this.begChangedAt);
        }
        if (this.endChangedAt != null){
        	fields.put("endChangedAt", this.endChangedAt);
        }

        if (this.begExpireOn != null){
        	fields.put("begExpireOn",this.begExpireOn);
        }
        if (this.endExpireOn != null){
        	fields.put("endExpireOn", this.endExpireOn);
        }
        
	    fields.put("active", this.findByStatus);
		
	    this.teachers = this.userService.searchTeachers(fields);

		if((this.teachers).isEmpty()){
			this.showInfoMessage(	this.localizedText("SearchCompleted"),
									this.localizedText("NoEntrysFounded"));
		}else{
			this.showInfoMessage(	this.localizedText("SearchCompleted"),
									this.teachers.size() + " " + 
									this.localizedText("entrysFounded"));
		}
	}
	

	
	public void deleteTeacher(){
		
		try{
			userService.deleteTeacher(teacher);
			this.showInfoMessage(	this.localizedText("Deleted"),
									this.localizedText("UserDeletedWithSuccess"));
			this.teachers.remove(this.teacher);
			this.teacher = null;
		}catch(ExceptionService e){
			this.showErrorMessage(this.localizedText("DeleteError"),
					e.getLocalizedMessage());
		}
		
	}
	
	
	public void toAddTeacher(){
		this.teacher  = new Teacher();
		
		this.teacher.setPhoto(userService.copyDefaultUserPhoto());

		this.teacher.setAcademy(this.getActiveActor(Academy.class));
		
		this.teacher.getUser().setLibrarys(libraryService.copyPublicLibrarys());
		
	}
	
	public void toAddPhoto(){
		
	}
	
	public List<Teacher> getTeachers() {
		return teachers;
	}

	public Teacher getSelTeacher() {
		return selTeacher;
	}

	public Teacher getTeacher() {
		return teacher;
	}

	public void setTeachers(List<Teacher> teachers) {
		this.teachers = teachers;
	}

	public void setSelTeacher(Teacher selTeacher) {
		this.selTeacher = selTeacher;
	}

	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}


	public int getUploadType() {
		return uploadType;
	}

	public void setUploadType(int uploadType) {
		this.uploadType = uploadType;
	}


	public Date getBegCreatedAt() {
		return begCreatedAt;
	}

	public Date getEndCreatedAt() {
		return endCreatedAt;
	}

	public Date getBegChangedAt() {
		return begChangedAt;
	}

	public Date getEndChangedAt() {
		return endChangedAt;
	}

	public String getFindByName() {
		return findByName;
	}


	public String getFindByEmail() {
		return findByEmail;
	}

	public boolean isFindByStatus() {
		return findByStatus;
	}

	public void setBegCreatedAt(Date begCreatedAt) {
		this.begCreatedAt = begCreatedAt;
	}

	public void setEndCreatedAt(Date endCreatedAt) {
		this.endCreatedAt = endCreatedAt;
	}

	public void setBegChangedAt(Date begChangedAt) {
		this.begChangedAt = begChangedAt;
	}

	public void setEndChangedAt(Date endChangedAt) {
		this.endChangedAt = endChangedAt;
	}

	public void setFindByName(String findByName) {
		this.findByName = findByName;
	}


	public void setFindByEmail(String findByEmail) {
		this.findByEmail = findByEmail;
	}

	public void setFindByStatus(boolean findByStatus) {
		this.findByStatus = findByStatus;
	}

	public String getFindByCpf() {
		return findByCpf;
	}

	public void setFindByCpf(String findByCpf) {
		this.findByCpf = findByCpf;
	}

	public String getFindByLastName() {
		return findByLastName;
	}

	public void setFindByLastName(String findByLastName) {
		this.findByLastName = findByLastName;
	}

	public Date getBegExpireOn() {
		return begExpireOn;
	}

	public Date getEndExpireOn() {
		return endExpireOn;
	}

	public void setBegExpireOn(Date begExpireOn) {
		this.begExpireOn = begExpireOn;
	}

	public void setEndExpireOn(Date endExpireOn) {
		this.endExpireOn = endExpireOn;
	}

	public EquipmentTableCompInterface getEquipmentTable() {
		return equipmentTable;
	}

	public void setEquipmentTable(EquipmentTableCompInterface equipmentTable) {
		this.equipmentTable = equipmentTable;
	}


}
